import Cell from "./Cell";

import { ColumnProps, TableStore } from '.';
import Colgroup from "./Colgroup";
import { PropType, computed, defineComponent, onBeforeUnmount, onMounted, onUnmounted, ref, watchEffect } from "vue";

type HeadProps = {
    data: TableStore,
    sticky?: boolean,
    onInitColumnWidth: (idx: number, width: number) => void,
    onResizeHeader: (width: number, height: number) => void,
    virtual?: boolean
}

export default defineComponent({
    name: 'Head',
    props: {
        data: {type: Object as PropType<HeadProps['data']>},
        sticky: {type: Boolean as PropType<HeadProps['sticky']>},
        onInitColumnWidth: {type: Function as PropType<HeadProps['onInitColumnWidth']>},
        onResizeHeader: {type: Function as PropType<HeadProps['onResizeHeader']>},
        virtual: {type: Boolean as PropType<HeadProps['virtual']>}
    },
    setup (props) {
        const thead = ref();
        const headerWrap = ref();
        // const onWrapEntry = (entry: ResizeObserverEntry) => {
        //     const el = entry.target;
        //     const index = el.getAttribute("data-index");

        //     if (index) {
        //         const idx = parseInt(index);
        //         if (el) {
        //             props.onInitColumnWidth(idx, el.getBoundingClientRect().width);
        //         }
        //     }
        // };
        const onHeadEntry = (entry: ResizeObserverEntry) => {
            const el = entry.target;
            if (el.tagName === 'THEAD') {
                const rect = el.getBoundingClientRect();
                props.onResizeHeader(rect.width, rect.height);
                if (headerWrap.value) {
                    headerWrap.value.style.height = rect.height + 'px';
                }
            } else {
                // setTimeout, header变化让body设置height后再计算是否有垂直滚动条
                setTimeout(() => {
                    const rect = el.getBoundingClientRect();
                    const parentRect = el.closest(".cm-table-body")!.getBoundingClientRect();

                    if (rect.height > parentRect.height) {
                        headerWrap.value.style.overflowY = 'scroll';
                    } else {
                        headerWrap.value.style.overflowY = '';
                    }
                });
            }
        };

        // const ro = new ResizeObserver((entries) => {
        //     entries.forEach((entry) => onWrapEntry(entry));
        // });
        // const ro2 = new ResizeObserver((entries) => {
        //     entries.forEach((entry) => onHeadEntry(entry));
        // });

        // onBeforeUnmount(() => {
        //     const childs = thead.value.querySelectorAll('th');
        //     const len = childs.length;
        //     for (let i = 0; i < len; i++) {
        //         childs[i] && ro.unobserve(childs[i]);
        //     }

        //     ro2.unobserve(thead);
        //     const parent = thead.value.closest('.cm-table');
        //     const body = parent && parent.querySelector('.cm-table-body-wrap');
        //     if (body) {
        //         ro2.unobserve(body);
        //     }
        // });

        onMounted(() => {
            const ro2 = new ResizeObserver((entries) => {
                entries.forEach((entry) => onHeadEntry(entry));
            });
            ro2.observe(thead.value);
            const parent = thead.value.closest('.cm-table');
            const body = parent.querySelector('.cm-table-body-wrap');
            ro2.observe(body);
            onBeforeUnmount(() => {
                ro2.unobserve(thead.value);
                ro2.unobserve(body);
            });
        });

        const headStyle: any = computed(() => ({
            'position': props.sticky ? 'sticky' : '',
            // position: 'absolute',
            'top': 0,
            'z-index': 2,
            'min-width': '100%',
            'overflow-x': 'hidden'
        }));

        watchEffect(() => {
            const left = props.data.headerLeft;
            if (headerWrap.value) {
                headerWrap.value.scrollLeft = left;
            }
        });

        return () => <div class="cm-table-header" style={headStyle.value} ref={headerWrap}>
            <table>
                <Colgroup data={props.data}/>
                <thead ref={thead}>
                    {
                        props.data.columnsRows.map((row: ColumnProps[], rowIndex) => {
                            return <tr>
                                {
                                    row.map((col: ColumnProps, index) => {
                                        return <Cell colSpan={col._colspan} rowSpan={col._rowspan} column={col} type="th" showFixedLeft={props.data.showFixedLeft} colIndex={index}
                                            showFixedRight={props.data.showFixedRight} checkedAll={props.data.checkedAll} ref={(el: Element) => {
                                            }}/>;
                                    })
                                }
                            </tr>;
                        })
                    }
                </thead>
            </table>
        </div>;
    }
});
